package com.shy.datasource;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.mysql.cj.jdbc.MysqlXADataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;

import com.shy.config.DB1Config;

@Configuration
@MapperScan(basePackages = {"com.shy.mapper.db1"}, /*sqlSessionFactoryRef = "sqlSessionFactoryDb1"*/ sqlSessionTemplateRef = "sqlSessionTemplateDb1")
public class DbSessionFactory1 {

	@Bean(name = "db1")
	public DataSource businessDbDataSource(@Qualifier("DB1Config") DB1Config db1Config) throws SQLException {
		MysqlXADataSource mysqlXADataSource = new MysqlXADataSource();
		mysqlXADataSource.setUrl(db1Config.getJdbcUrl());
		mysqlXADataSource.setUser(db1Config.getUsername());
		mysqlXADataSource.setPassword(db1Config.getPassword());
		mysqlXADataSource.setPinGlobalTxToPhysicalConnection(true);

		AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
		xaDataSource.setXaDataSource(mysqlXADataSource);
		xaDataSource.setUniqueResourceName("db1");

		return xaDataSource;
	}

	@Bean(name="sqlSessionFactoryDb1")
	public SqlSessionFactory sqlSessionFactoryDb1(@Qualifier("db1")DataSource dataSource) throws Exception {
		SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
		factoryBean.setDataSource(dataSource);
		return factoryBean.getObject();
	}

	@Bean(name="sqlSessionTemplateDb1")
	public SqlSessionTemplate sqlSessionTemplateDb1(@Qualifier("sqlSessionFactoryDb1") SqlSessionFactory sqlSessionFactory) throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}
}
